// src/lib/TianMapApi.js
const TianMapApi = {
    map: null,
    marker: null,
    isReady: false,
    clickCallback: null,
  
    CreateMap(domId, zoom = 15) {
      const T = window.T;
      if (!T) {
        console.error('天地图 API 未加载');
        return;
      }
  
      this.map = new T.Map(domId);
      const center = new T.LngLat(106.5823, 29.56593);
      this.map.centerAndZoom(center, zoom);
      this.map.addControl(new T.Control.Zoom());
  
      // 添加图层
    //   const vecLayer = new T.TileLayer(
    //     `${import.meta.env.VITE_TIANDITU_PROXY_T1}/DataServer?T=vec_w&x={x}&y={y}&l={z}&tk=${import.meta.env.VITE_TIANDITU_KEY}`
    //   );
    //   this.map.addLayer(vecLayer);
  
    //   const labelLayer = new T.TileLayer(
    //     `${import.meta.env.VITE_TIANDITU_PROXY_T1}/DataServer?T=cia_w&x={x}&y={y}&l={z}&tk=${import.meta.env.VITE_TIANDITU_KEY}`
    //   );
    //   this.map.addLayer(labelLayer);
  
      // 添加标注
    //   this.addMarker(lng, lat);
  
      this.isReady = true;
      return this.map;
    },

    // 区添加边框
    addCountyBorder(coordinates) {
      const T = window.T;
      if (!this.map || !T) return;
      const arr = coordinates[0][0]?.map(item => {
        return new T.LngLat(item[0], item[1])
      }) ?? []
      let polygon = new T.Polygon(arr, {
        color: '#ff0000',
        weight: 2,
        opacity: 1,
        fillColor: '#FFFFFF',
        fillOpacity: 0.1,
      });

      this.map.addOverLay(polygon);
    },
  
    addMarker(lng, lat) {
      const T = window.T;
      if (!this.map || !T) return;
  
      const point = new T.LngLat(lng, lat);
      if (!this.marker) {
        this.marker = new T.Marker(point);
        this.map.addOverLay(this.marker);
      } else {
        this.marker.setLngLat(point);
      }
    },
  
    removeMarker() {
      if (this.marker && this.map) {
        this.map.removeOverLay(this.marker);
        this.marker = null;
      }
    },
  
    clearOverLays() {
      if (this.map) {
        this.map.clearOverLays();
        this.marker = null;
      }
    },
  
    onClick(callback) {
      if (!this.map) return;
  
      this.offClick(); // 先解绑，避免重复绑定
  
      this.clickCallback = (e) => {
        const point = e.lnglat;
        callback([point.lng, point.lat]);
      };
  
      this.map.on('click', this.clickCallback);
    },
  
    offClick() {
      if (this.map && this.clickCallback) {
        this.map.off('click', this.clickCallback);
        this.clickCallback = null;
      }
    },
  
    getAddressByXY([lng, lat], callback) {
      const key = import.meta.env.VITE_TIANDITU_KEY;
      const url = `https://api.tianditu.gov.cn/geocoder?postStr={"lon":${lng},"lat":${lat},"ver":1}&type=geocode&tk=${key}`;
  
      fetch(url)
        .then((res) => res.json())
        .then((data) => {
          if (data?.result?.formatted_address) {
            callback({
              info: 'OK',
              regeocode: {
                formattedAddress: data.result.formatted_address,
                addressComponent: {
                  adcode: data.result.addressComponent.adcode,
                  district: data.result.addressComponent.district,
                  township: data.result.addressComponent.township,
                  towncode: data.result.addressComponent.towncode,
                },
              },
            });
          } else {
            callback({ info: 'FAIL' });
          }
        })
        .catch(() => {
          callback({ info: 'FAIL' });
        });
    },
  };
  
  export default TianMapApi;
  